import cv2
import numpy as np

def apply_night_vision_effect(frame):
    # 转为灰度
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Gamma 校正（提高亮度区域对比度）
    gamma = 0.6
    invGamma = 1.0 / gamma
    table = np.array([(i / 255.0) ** invGamma * 255 for i in range(256)]).astype("uint8")
    adjusted = cv2.LUT(gray, table)

    # 应用高斯模糊突出发光
    blurred = cv2.GaussianBlur(adjusted, (0, 0), sigmaX=3)
    glow = cv2.addWeighted(adjusted, 0.8, blurred, 0.2, 0)

    # 合成绿色夜视风格 (gray -> BGR -> Tint Green)
    night_vision = cv2.merge([
        glow * 0.1,     # Blue
        glow * 1.0,     # Green
        glow * 0.1      # Red
    ])
    night_vision = np.clip(night_vision, 0, 255).astype("uint8")

    return night_vision

def process_video_night_vision(input_path, output_path):
    cap = cv2.VideoCapture(input_path)
    if not cap.isOpened():
        print("无法打开视频文件")
        return

    # 视频参数
    width  = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    fps    = cap.get(cv2.CAP_PROP_FPS)
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    out    = cv2.VideoWriter(output_path, fourcc, fps, (width, height))

    print("正在处理视频为夜视模式...")

    frame_count = 0
    while True:
        ret, frame = cap.read()
        if not ret:
            break

        night_frame = apply_night_vision_effect(frame)
        out.write(night_frame)

        frame_count += 1
        if frame_count % 30 == 0:
            print(f"已处理帧数：{frame_count}")

    cap.release()
    out.release()
    print("夜视视频处理完成，结果保存在：", output_path)

# ========== 主程序入口 ==========
if __name__ == "__main__":
    input_video = "video1.mp4"
    output_video = "output_night_vision.mp4"
    process_video_night_vision(input_video, output_video)
